// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//
#include <pollux/expression/expr.h>
#include <pollux/expression/vector_function.h>
#include <pollux/functions/lib/lambda_function_util.h>
#include <pollux/functions/lib/rows_translation_util.h>
#include <pollux/vector/function_vector.h>

namespace kumo::pollux::functions {
    namespace {
        // See documentation at https://prestodb.io/docs/current/functions/array.html
        class TransformFunction : public exec::VectorFunction {
        public:
            void apply(
                const SelectivityVector &rows,
                std::vector<VectorPtr> &args,
                const TypePtr &outputType,
                exec::EvalCtx &context,
                VectorPtr &result) const override {
                POLLUX_CHECK_EQ(args.size(), 2);

                // Flatten input array.
                exec::LocalDecodedVector arrayDecoder(context, *args[0], rows);
                auto &decodedArray = *arrayDecoder.get();

                auto flatArray = flattenArray(rows, args[0], decodedArray);

                std::vector<VectorPtr> lambdaArgs = {flatArray->elements()};
                auto newNumElements = flatArray->elements()->size();

                SelectivityVector validRowsInReusedResult =
                        toElementRows<ArrayVector>(newNumElements, rows, flatArray.get());

                // transformed elements
                VectorPtr newElements;

                auto elementToTopLevelRows = getElementToTopLevelRows(
                    newNumElements, rows, flatArray.get(), context.pool());

                // loop over lambda functions and apply these to elements of the base array;
                // in most cases there will be only one function and the loop will run once
                auto it = args[1]->as_unchecked<FunctionVector>()->iterator(&rows);
                while (auto entry = it.next()) {
                    auto elementRows = toElementRows<ArrayVector>(
                        newNumElements, *entry.rows, flatArray.get());
                    auto wrapCapture = toWrapCapture<ArrayVector>(
                        newNumElements, entry.callable, *entry.rows, flatArray);

                    entry.callable->apply(
                        elementRows,
                        &validRowsInReusedResult,
                        wrapCapture,
                        &context,
                        lambdaArgs,
                        elementToTopLevelRows,
                        &newElements);
                }

                // Set nulls for rows not present in 'rows'.
                BufferPtr newNulls = addNullsForUnselectedRows(flatArray, rows);

                VectorPtr localResult = std::make_shared<ArrayVector>(
                    flatArray->pool(),
                    outputType,
                    std::move(newNulls),
                    rows.end(),
                    flatArray->offsets(),
                    flatArray->sizes(),
                    newElements);
                context.moveOrCopyResult(localResult, rows, result);
            }

            static std::vector<std::shared_ptr<exec::FunctionSignature> > signatures() {
                // array(T), function(T, U) -> array(U)
                return {
                    exec::FunctionSignatureBuilder()
                    .typeVariable("T")
                    .typeVariable("U")
                    .returnType("array(U)")
                    .argumentType("array(T)")
                    .argumentType("function(T, U)")
                    .build()
                };
            }
        };
    } // namespace

    /// transform is null preserving for the array. But since an
    /// expr tree with a lambda depends on all named fields, including
    /// captures, a null in a capture does not automatically make a
    /// null result.

    POLLUX_DECLARE_VECTOR_FUNCTION_WITH_METADATA(
        udf_transform,
        TransformFunction::signatures(),
        exec::VectorFunctionMetadataBuilder().defaultNullBehavior(false).build(),
        std::make_unique<TransformFunction>());
} // namespace kumo::pollux::functions
